<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>02-相机运动</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";

      //创建场景
      const scene = new THREE.Scene();
      //   scene.background = new THREE.Color(0xc89e06b); //背景颜色
      const loader = new THREE.TextureLoader();
      loader.load("../images/1.png", function (texture) {
        scene.background = texture;
      }); //设置背景图片

      //创建相机
      const camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      //设置相机位置
      //   camera.position.x = 2;
      //   camera.position.z = 3;
      camera.position.set(0, 4, 10); //统一设置
      //设置相机朝向点位
      camera.lookAt(0, 0, 0);

      //创建渲染器
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      //创建物体
      const cube1 = new THREE.Mesh(
        new THREE.BoxGeometry(1, 1, 1),
        new THREE.MeshBasicMaterial()
      );
      const cube2 = new THREE.Mesh(
        new THREE.BoxGeometry(1, 1, 1),
        new THREE.MeshBasicMaterial({
          color: 0xc424,
        })
      );
      cube2.position.x = 2;
      scene.add(cube1); //在场景中添加物体
      scene.add(cube2); //在场景中添加物体

      //渲染
      renderer.render(scene, camera);

      let angle = 0; //角度
      //动画函数
      function animate() {
        requestAnimationFrame(animate);
        cube1.rotation.x += 0.01;
        cube1.rotation.y += 0.01;

        angle += 0.01;
        //设置相机位置，让相机运动起来
        const radius = 3;
        camera.position.x = radius * Math.cos(angle);
        camera.position.z = radius * Math.sin(angle);
        camera.lookAt(0, 0, 0);
        renderer.render(scene, camera);
      }
      animate();
    </script>
  </body>
</html>
